import Axios from 'axios';
import $store from '@/store';
import $router from '@/router';
import {Toast, Dialog} from 'vant';
import md5 from 'js-md5';

const $http = Axios.create({
    baseURL: '/api'
});

// Before request
$http.interceptors.request.use(
    config => {
        if(!config.headers.Authorization){
            var token = window.localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = token;  //放置headers的Authorization里
                // config.headers.Token = token;       //放置headers的Token里
            }
        }
        
        // var token = this.$route.query.token
        config.url = config.url + '?time=' + Date.parse(new Date()).toString().substr(0, 10) + '&sign=' + md5("qdcrowdfundingqd" + Date.parse(new Date()).toString().substr(0, 10));
        
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// After request
$http.interceptors.response.use(
    response => {
        Toast.clear();

        const data = response.data;

        switch (data.status)
        {
			// Success
			case 200:
				data.message != '' && data.message != 'OK' && data.message != 'ok' && Toast(data.message);
				return data;

            // Error
            case 400:
                data.message !== '' && Toast(data.message);
                return new Promise(() => {});

            // No access
            case 403:
            // 404
            case 404:
            // Fail
            case 500:
                Dialog.alert({
                    message: data.message
                }).then(() => {
                    $router.back();
                });

                return new Promise(() => {});

            // not logged
            case 100:
                data.message != '' && Toast.fail(data.message);
                $store.dispatch('logout');
                $router.replace('/login?redirect=' + $router.currentRoute.fullPath);
                return new Promise(() => {});

            default:
                Dialog.alert({message: data});
                return new Promise(() => {});
        }
    },
    error => {
        Toast.clear();

        Dialog.alert({
            title: 'Error',
            message: error.message
        }).then(() => {
            $router.back();
        });

        return Promise.reject(error);
    }
);

export default $http;
